package javase2.day06;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.LinkedList;
import java.util.Scanner;

public class Demo7 {
	public static void main(String[] args) throws IOException{
		String file = "unsync.txt";
		final LinkedList<String> buf = new LinkedList<String>();
		final Scanner console = new Scanner(System.in);
		final PrintWriter out = new PrintWriter(file);

		//检查缓冲区中的信息，如果有信息，就写入文件中
		final Thread writer = new Thread(){
			public void run(){
				while(true){
					if(buf.isEmpty()){
						try {
							System.out.println("sleep 5");
							Thread.sleep(5000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						continue;
					}
					String str = buf.removeFirst();
					System.out.println("写入："+str);
					out.println(str);
					out.flush(); //清空缓冲区，保证可靠写入
				}
			}
		};
		final Thread reader = new Thread(){
			public void run(){
				for(;;){
					String str = console.nextLine();
					buf.addLast(str);
					if(str.equalsIgnoreCase("bye")){
						writer.interrupt();
						break;
					}
				}
			}
		};
		writer.setDaemon(true); //reader线程结束时，writer线程被结束
		writer.start();
		reader.start();
	}
}
